package com.csdj.springboottest.endpoint;

import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
@ServerEndpoint("/ws/test")
public class WebSocketTest {

    private static Map<String, Session> sessions = new ConcurrentHashMap<>();

    /**
     * 连接事件， 当客户主动连接服务端时触发
     * @param session
     */
    @OnOpen
    public void onOpen(Session session){
        sessions.put(session.getId(),session);
        System.out.println(sessions.size());
        System.out.println("有客户进行连接 id："+session.getId());
    }

    /**
     * 当客户端主动关闭连接时触发此方法
     * @param session
     */
    @OnClose
    public void onClose(Session session){
        sessions.remove(session);
        System.out.println("客户已经关闭了连接  id:"+session.getId());
    }

    /**
     * 当客户端向服务端发送消息的时， 触发方法
     * @param session
     * @param msg 消息内容
     */
    @OnMessage
    public void onMessage(String msg, Session session){
        System.out.println("接受客户端的消息："+msg);
        //把消息返回给客户端
//        send(msg,session);
        msg = session.getId()+":"+msg;
        sendAll(msg);
    }

    /**
     * 当连接发生异常时触发此方法
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error){
        sessions.remove(session);
        System.out.println("连接发生了异常  id:"+session.getId());
        System.out.println("异常信息："+error.getMessage());
    }

    public void sendAll(String msg){
        System.out.println("session的大小:"+sessions.size());
        sessions.values().parallelStream().forEach(s -> {
            send(msg,s);
            System.out.println(s.getId());
        });
    }


    public void send(String msg, Session session){
        if(session.isOpen()){
            try {
                session.getBasicRemote().sendText(msg);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            System.out.println("连接已经关闭");
        }
    }
}
